﻿
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Text;
using Traceability.App.API.Extensions;
using Traceability.App.Infrastructrue;
using Traceability.App.Infrastructrue.Implement;
using Traceability.App.Infrastructrue.Interface;

namespace Traceability.App.API.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册中介者
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection MediatR(this IServiceCollection services)
        {
            services.AddMediatR(cfg =>
            {
                cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly());
            });
            return services;
        }
        /// <summary>
        /// AutoMapper
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AutoMapper(this IServiceCollection services)
        {
            return services.AddAutoMapper(typeof(MyAutoMapper));
        }
        /// <summary>
        /// Scoped
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddScoped(this IServiceCollection services)
        {
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            return services;
        }
        /// <summary>
        /// 连接字符串
        /// </summary>
        /// <typeparam name="WorkDbContrxt">EF上下文</typeparam>
        /// <param name="services">扩展的类型</param>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="enableSqlLog">是否打印执行EF语句转义的sql</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<WorkDbContrxt>(this IServiceCollection services, string? connectionString, bool enableSqlLog) where WorkDbContrxt : DbContext
        {
            return services.AddDbContext<AppDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                            maxRetryCount: 10,
                            maxRetryDelay: TimeSpan.FromSeconds(60),
                            errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((categoty, level) => categoty == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).
                        AddConsole();
                    }));
                }
            });
        }
    }
}
